<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="params.keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="treeDom"
          node-key="id"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button
            v-permission="'add-employee'"
            size="mini"
            type="primary"
            @click="$router.push('/employee/detail')"
          >添加员工</el-button>
          <el-button
            size="mini"
            @click="showExcelDialog = true"
          >excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="tableData">
          <el-table-column prop="staffPhoto" label="头像" width="120">
            <template #default="{ row }">
              <el-avatar
                v-if="row.staffPhoto"
                :size="30"
                :src="row.staffPhoto"
              />
              <!-- <span v-else class="username">{{ row.username?.charAt(0) }}</span> -->
              <span v-else class="username">{{
                row.username?.substr(-1)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column prop="mobile" label="操作">
            <template #default="{ row }">
              <el-button
                type="text"
                size="mini"
                @click="$router.push(`/employee/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="mini" @click="btnRole(row.id)">角色</el-button>
              <template>
                <el-popconfirm
                  title="确定删除当前员工吗？"
                  @onConfirm="delConfirm(row.id)"
                >
                  <el-button
                    slot="reference"
                    type="text"
                    size="mini"
                    style="margin-left: 10px"
                  >删除</el-button>
                </el-popconfirm>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :current-page="params.page"
            :page-size="params.pagesize"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </div>
    </div>
    <uploadExcelVue
      :show-excel-dialog.sync="showExcelDialog"
      @updateData="getTableData"
    />
    <el-dialog :visible.sync="showRoleDialog" title="分配角色">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox
          v-for="item in roleList"
          :key="item.id"
          :label="item.id"
        >{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnRoleOK">确定</el-button>
          <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getDeparment } from '@/api/deparment'
import { getEmpList, exportEmployee, delUser, getEnableRoleList, getEmployeeDetail, assignRole } from '@/api/employee'
import { transList2TreeData } from '@/utils'
import FileSaver from 'file-saver'
import uploadExcelVue from './uploadExcel.vue'
export default {
  name: 'Employee',
  components: {
    uploadExcelVue
  },
  data() {
    return {
      currentUserId: null,
      depts: [],
      defaultProps: {
        label: 'name'
      },
      params: {
        page: 1,
        pagesize: 10,
        keyword: '',
        departmentId: null // 部门id
      },
      tableData: [],
      total: 0,
      showExcelDialog: false,
      showRoleDialog: false, // 用来控制角色弹层的显示
      roleList: [], // 接收角色列表
      roleIds: [] // 用来双向绑定数据的
    }
  },
  created() {
    this.getTreeList()
  },
  methods: {
    async btnRoleOK() {
      await assignRole({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.showRoleDialog = false
      this.$message.success('分配用户角色成功')
    },
    // 角色列表
    async btnRole(id) {
      this.roleList = await getEnableRoleList()
      this.currentUserId = id
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
      this.showRoleDialog = true
    },
    async getTreeList() {
      this.depts = transList2TreeData(await getDeparment(), 0)
      // 默认第一条数据为首个节点id
      this.params.departmentId = this.depts[0].id
      // 数据获取异步
      this.$nextTick(() => {
        // 默认选中当前节点
        this.$refs.treeDom.setCurrentKey(this.params.departmentId)
      })
      this.getTableData()
    },
    // 选中节点变化时触发————》切换部门
    selectNode(node) {
      this.params.departmentId = node.id
      this.params.page = 1
      this.getTableData()
    },
    async getTableData() {
      const { rows, total } = await getEmpList(this.params)
      this.tableData = rows
      this.total = total
    },
    // 分页
    handleCurrentChange(val) {
      this.params.page = val
      this.getTableData()
    },
    // 模糊搜索
    changeValue() {
      // 使用防抖  指触发事件后的 n 秒后会执行一次函数，如果此期间又触发了事件，则会重新计时
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.params.page = 1
        this.getTableData()
      }, 500)
    },
    // 导出
    async exportEmployee() {
      const res = await exportEmployee()
      console.log(res)
      // FileSaver.saveAs(blob对象,文件名称)
      FileSaver.saveAs(res, '员工信息表.xlsx')
    },
    // 删除
    async delConfirm(id) {
      await delUser(id)
      this.$message.success('删除员工成功')
      if (this.tableData.length === 1) this.params.page--
      this.getTableData()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
